package com.example.mydefinedview1

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import androidx.annotation.LayoutRes


/**
 * A simple [Fragment] subclass.
 * Use the [PageFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class PageFragment : Fragment() {
    @LayoutRes var sampleLayout:Int? = null
    @LayoutRes var practiceLayoutRes:Int = 0

    companion object{
        fun newInstance(@LayoutRes sampleLayoutRes:Int,@LayoutRes practiceLayoutRes:Int):PageFragment{
            val fragment = PageFragment()
            val bundle = Bundle()
            bundle.putInt("sampleLayoutRes",sampleLayoutRes)
            bundle.putInt("practiceLayoutRes",practiceLayoutRes)
            fragment.arguments = bundle
            return fragment
        }
    }

    //初始化显示数据
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bundle = arguments
        if (bundle != null){
            sampleLayout = bundle.getInt("sampleLayoutRes")
            practiceLayoutRes = bundle.getInt("practiceLayoutRes")
        }
    }

    //初始化显示控件
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_page, container, false)
        val sampleStub = view.findViewById<ViewStub>(R.id.sampleStub)
        sampleStub.layoutResource = sampleLayout!!
        //ViewStub 是一个看不见的，没有大小，不占布局位置的 View，可以用来懒加载布局
        //只有给他设置成了View.Visible或调用了它的inflate()之后才会填充布局资源
        //在 ViewStub 加载完成后就会被移除，它所占用的空间就会被新的布局替换。
        sampleStub.inflate()

        val practiceStub = view.findViewById<ViewStub>(R.id.practiceStub)
        practiceStub.layoutResource = practiceLayoutRes
        practiceStub.inflate()

        return view
    }


}